/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.push.ws;

import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;

import org.apache.cxf.jaxrs.ext.MessageContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Maps;

/**
 * xxx
 * 
 * @author Wangyi
 * @version v1.0
 * 
 * @date 2013-7-30
 * 
 */
public class PushWsExceptionMapper implements ExceptionMapper<Throwable> {

	private final static Logger log = LoggerFactory.getLogger(PushWsExceptionMapper.class);
	@Context
	private MessageContext mc;

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.ws.rs.ext.ExceptionMapper#toResponse(java.lang.Throwable)
	 */
	@Override
	public Response toResponse(Throwable exception) {
		log.error(exception.getMessage(), exception);
		ResponseBuilder builder = Response.status(Status.INTERNAL_SERVER_ERROR);
		Map<String, Object> result=Maps.newHashMap();
		result.put("error", generateErrorMessage(exception));
		builder.language("utf-8");
        builder.entity(result);
        return builder.build();
	}

	private String generateErrorMessage(Throwable exception) {
		HttpServletRequest request = mc.getHttpServletRequest();
		String errorKey = exception.getMessage();

		Locale locale = request.getLocale();
		ResourceBundle rb;
		try {
			rb = ResourceBundle.getBundle("com.foreveross.bsl.push.application.error", locale);
			String message = rb.getString(errorKey);
			if(message==null || message.trim().isEmpty()){
				message=errorKey;
			}
			return message;
		} catch (MissingResourceException e) {
			//找不到资源文件则忽略
			return errorKey;
		}
	}
}
